import Fly from 'flyio/dist/npm/wx';
// import { loginOut } from '@/utils/index';
const request = new Fly();

request.interceptors.request.use(config => {
  let token = wx.getStorageSync('token');
  if (token) {
    config.headers['Authorization'] = token;
  }
  return config;
});

request.interceptors.response.use(
  (response, promise) => {
    const Authorization = response.headers['Authorization'];
    if (Authorization != null) {
      wx.setStorageSync('token', Authorization);
      // store.commit('token', xAuthToken)
    }
    if (response.data.code === 418) {
      console.log(response.data.description);
      wx.showToast({
        title: response.data.description,
        icon: 'none',
        duration: 2000
      });
    }
    return promise.resolve(response.data);
  },
  (err, promise) => {
    console.log(err, 'rrrrr');
    /**
     * 401 未授权
     */
    if (err.status === 401) {
      wx.showToast({
        title: '暂无权限，请先登录',
        icon: 'none',
        duration: 1000,
        mask: true
      });
      if (wx.getStorageSync('userInfo')) {
        // wx.removeStorage('userInfo');
        wx.removeStorage({
          key: 'userInfo',
          success: (res) => {
            setTimeout(function () {
              wx.navigateTo({
                url: `/pages/PersonalCenter/userChildren/authorization/main`
              });
            }, 1000);
            // that.setData({
            //   storageData: []
            // });
          }
        });
      } else {
        setTimeout(function () {
          wx.navigateTo({
            url: `/pages/PersonalCenter/userChildren/authorization/main`
          });
        }, 1000);
      }
    } else {
      wx.showToast({
        title: '网络请求异常,请稍后再试！',
        icon: 'none',
        duration: 1000,
        mask: true
      });
    }
    // return promise.resolve(err.response);
  }
);
export default request;
